package com.qf.listener;

import com.qf.consants.RabbitMQConstants;
import com.qf.entity.Goods;
import com.rabbitmq.client.Channel;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class GoodsQueueItemListener {

    // 创建一个固定长度的线程池
    private ExecutorService executorService = Executors.newFixedThreadPool(5);

    @Autowired
    private FreeMarkerConfig freeMarkerConfig;

    @Value("http://localhost/shop-resources")
    private String basePath;

    @RabbitListener(queues = RabbitMQConstants.GOODS_QUEUE_ITEM)
    public void createImte(Goods goods, Channel channel, Message message) {
        System.out.println(goods);
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {

                    // 1.设置模板
                    Template template = freeMarkerConfig.getConfiguration().getTemplate("goods-item.ftl");
                    // 2.把数据封装到Map中
                    Map<String, Object> map = new HashMap<>();
                    map.put("goods", goods);
                    map.put("basePath", basePath);
                    if (!StringUtils.isEmpty(goods.getGpic())) {
                        map.put("gpicList", goods.getGpic().split("\\|"));
                    }

                    // 如何哎这里获取static的路径？？
                    // 获取当前项目的static路径
                    File file = ResourceUtils.getFile("classpath:static");

                    // 获取决定路径
                    String absolutePath = file.getAbsolutePath();

                    System.out.println(absolutePath);


                    // 3.利用模板引擎来生成静态html页面
                    template.process(map, new FileWriter(absolutePath + File.separator + goods.getId() + ".html"));

                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                } catch (Exception e) {
                    e.printStackTrace();
//                    try {
//                        channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
//                    } catch (IOException e1) {
//                        e1.printStackTrace();
//                    }
                }
            }
        });

    }
}
